from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.ext.webapp.util import run_wsgi_app

import logging
import urllib
import time

from meang import *

CINPLEXKEY = 'cinplex1'
SFKEY      = 'sfx1'
CENTURYKEY = 'cen1'
MAINKEY    = 'maindat7'
BRANCHES_CODE = ["PRG,SUK,RAT",
                "RM3,ESP,MPL",
                "IMX,RSE,AYA",
                "RST,CWN,NKB",
                "NKL,NON,TYB",
                "NWK,PKE,PIN",
                "RM2,PKS,AMY",
                "BKE,BPL,SLY",
                "MHC,BNA,SRG",
                "SCS,SNR,BKP",
                "FSI,LPO,RAM",
                "NSW,PSL,CHM",
                "PCB,PTY,CHN",
                "CCS,SRA,AMK",
                "HUH,SMU,KBI",
                "UDN,KRT,UBN,SRB"]

URL = "http://www.majorcineplex.com/showtimepage.php?searchmode=1&movie=--Select+Movie--&branch=%s&showdate=%s"
SF_URL = "http://m.sfcinemacity.com:8080/m_sfcinemacity_com/CShowTimes03.jsp?cinema=%d&movie=0"
CENTURY_URL = "http://www.centurythemovieplaza.com/showtime.php"

def prepare_sf():
    rpclist = []
    for bcode in range(1,22):
        content = ''
        url = SF_URL % bcode
        rpc = urlfetch.create_rpc(deadline=10)
        urlfetch.make_fetch_call(rpc, url)
        rpclist.append(rpc)
    for bcode,rpc in zip(range(1,22),rpclist):
        bcode = 'SFX-%d' % bcode
        try:
            logging.debug('fetching')
            res = rpc.get_result()
            if res.status_code == 200:
                try:
                    current = format_sf([res.content])
                    memcache.set(bcode,current)
                except:
                    #current = 'ERR'+bcode
                    continue
                
                content += current
            else:
                oldval = memcache.get(bcode)
                if oldval != None:
                    content += oldval
        except urlfetch.DownloadError:
            oldval = memcache.get(bcode)
            if oldval != None:
                content += oldval   
    return content

def prepare_cineplex():
    content = ''
    rpclist = []
    today = time.strftime('%d/%m/%Y',time.localtime(time.time()+25200))
    for bcode in BRANCHES_CODE:
        logging.debug('RPC')
        rpc = urlfetch.create_rpc(deadline=10)
        urlfetch.make_fetch_call(rpc, URL %(bcode,today))
        rpclist.append(rpc)
    for bcode,rpc in zip(BRANCHES_CODE,rpclist):
        bcode = 'CINE--%s' % bcode
        try:
            logging.debug('fetching')
            res = rpc.get_result()
            if res.status_code == 200:
                content += res.content
                memcache.set(bcode,res.content)
            else:
                oldval = memcache.get(bcode)
                if oldval != None:
                    content += oldval
        except urlfetch.DownloadError:
            oldval = memcache.get(bcode)
            if oldval != None:
                content += oldval
    s = process_cineplex(content)
    out = format_cineplex(s)
    memcache.set(CINPLEXKEY,out)
    return out
    
def prepare_century():
    try:
        res = urlfetch.fetch(CENTURY_URL,deadline=10)
        content = format_century(res.content)
        memcache.set(CENTURYKEY,content)
    except:
        content = memcache.get(CENTURYKEY)
        if content == None:
            content = ''
    return content
    
APEX_URL = 'http://www.apexsiam-square.com/home.asp'
APEX_KEY = 'apexxxx'

def prepare_apex():
    try:
        res = urlfetch.fetch(APEX_URL,deadline=10)
        content = format_apex(res.content)
        memcache.set(APEX_KEY,content)
    except:
        content = memcache.get(APEX_KEY)
        if content == None:
            content = ''
    return content
    
VISTA_URL = 'http://vistashowtime.blogspot.com/'
VISTA_KEY = 'vista_chiangmai'

def prepare_vista():
    try:
        res = urlfetch.fetch(VISTA_URL,deadline=10)
        content = format_vista(res.content)
        memcache.set(VISTA_KEY,content)
    except:
        content = memcache.get(VISTA_KEY)
        if content == None:
            content = ''
    return content
    
DIANA_URL = 'http://www.diana.co.th/movie_main.php'
DIANA_KEY = 'diana_hatyai'

def prepare_diana():
    try:
        res = urlfetch.fetch(DIANA_URL,deadline=10)
        content = format_diana(res.content)
        memcache.set(DIANA_KEY,content)
    except:
        content = memcache.get(DIANA_KEY)
        if content == None:
            content = ''
    return content
    
def prepare_cache():
    final = HTML_HEADER
    final += '<h1>Last fetched:'+time.strftime('%d-%m-%Y %H:%M',time.localtime(time.time()+25200))+'</h1>\n'
    final += '<div id="main">\n'
    final += prepare_apex()
    final += prepare_century()
    final += prepare_vista()
    final += prepare_diana()
    final += prepare_sf()
    final += prepare_cineplex()
    final += '</div>\n'
    final += HTML_FOOTER
    memcache.set(MAINKEY,final)

class MajorLoader(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        prepare_cache()
        self.response.out.write('Completed')

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        maindat = memcache.get(MAINKEY)
        #while maindat == None:
        #    prepare_cache()
        #    maindat = memcache.get(MAINKEY)
        if maindat == None:
            self.response.out.write(format_error())
        else:
            self.response.out.write(maindat)
            
class TheatrePage(webapp.RequestHandler):
    def get(self,tname):
        memcache.get('_'+tname)
                    
application = webapp.WSGIApplication(
    [
        (ur'/', MainPage),
        (ur'/_load', MajorLoader),
        (ur'/([\w\_]+)',TheatrePage)
    ],
    debug=True)

def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
